import os
import urllib.parse
import urllib.request
import jsonpath
from global_conf import config
from utils import VERSION_RE, Browser_type, Manager


class Chrome(Manager):

    '''
        自动匹配Chrome浏览器版本下载ChromeDriver

    '''

    def __init__(self, file):
        self.conf = super().get_ini(file)
        self.absPath = config.DRIVER_PATH
        self.url = self.conf.get('DRIVER', 'url')
        self.check_match_chrome()
        self.chmod(self.absPath)

    def chromedriver_version(self):
        cmd = r'{} --version'.format(self.absPath)
        if(os.path.exists(self.absPath)):
            output = super().shell(cmd)
            self.chmod(self.absPath)
            try:
                __v__ = VERSION_RE.findall(output.split(' ')[1])[0]
                print(f'current chromedriver Version: \033[0;33;40m{__v__}\033[0m')
                return __v__
            except Exception as e:
                print(f'check chromedriver failed: \033[0;31;40m{e}\033[0m')
                return 0
        else:
            print(f'check chromedriver failed: chrome driver is not exists!')
            return 0

    def check_match_chrome(self):
        print('check Chrome and chromedriver wheather are matched')
        c_v = super().browser_version(Browser_type.GOOGLE)
        d_v = self.chromedriver_version()
        if c_v == d_v:
            print('Chrome version is:',c_v)
            print('\033[0;32;40mChrome and chromedriver are matched.\033[0m')
        else:
            print('Chrome version is:', c_v)
            save_d = os.path.dirname(self.absPath)
            self.get_chromedriver(c_v, save_d)

    def get_chromedriver(self, __v, save_d):
        ot = 'win32' if 'win' in self.os_type else self.os_type
        rep = urllib.request.urlopen(self.url).read().decode('utf-8')
        names = jsonpath.jsonpath(eval(rep),"$..name")
        for name in names:
            if __v in name:
                driver_name = name + f'/chromedriver_{ot}.zip'
                down_uri = urllib.parse.urljoin(self.url, driver_name)
                super().download_file(down_uri, save_d)
                break


if __name__ == '__main__':
    Chrome(os.path.join(config.BASE_DIR,'config.ini'))